import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserManageFrame extends JFrame {
    private JTable userTable;
    private DefaultTableModel tableModel;

    public UserManageFrame() {
        setTitle("用户管理");
        setSize(600, 400);
        setLocationRelativeTo(null);

        // 初始化表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("编号");
        tableModel.addColumn("用户名");
        tableModel.addColumn("角色");

        userTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(userTable);

        // 初始化按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加用户");
        JButton editBtn = new JButton("编辑用户");
        JButton deleteBtn = new JButton("删除用户");
        JButton resetPwdBtn = new JButton("重置密码");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(resetPwdBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadUserData();

        // 设置事件监听
        addBtn.addActionListener(e -> {
            new UserEditDialog(null).setVisible(true);
            loadUserData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = userTable.getSelectedRow();
            if (selectedRow >= 0) {
                String username = (String) tableModel.getValueAt(selectedRow, 1);
                new UserEditDialog(username).setVisible(true);
                loadUserData();
            } else {
                showWarningDialog("请选择要修改的行");
            }
        });

        deleteBtn.addActionListener(e -> deleteUser());
        resetPwdBtn.addActionListener(e -> resetPassword());
        refreshBtn.addActionListener(e -> loadUserData());
    }

    /**
     * 加载用户数据
     */
    private void loadUserData() {
        tableModel.setRowCount(0); // 清空表格

        String sql = "SELECT id, username, role FROM users";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("id"),
                        rs.getString("username"),
                        rs.getString("role")
                });
            }
        } catch (SQLException e) {
            showErrorDialog("加载数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 删除用户
     */
    private void deleteUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow >= 0) {
            String username = (String) tableModel.getValueAt(selectedRow, 1);

            int confirm = showConfirmDialog(
                    "确定要删除用户 " + username + " 吗?",
                    "确认删除");

            if (confirm == JOptionPane.YES_OPTION) {
                String sql = "DELETE FROM users WHERE username = ?";

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement(sql)) {

                    pstmt.setString(1, username);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        showMessageDialog("删除成功");
                        loadUserData();
                    }
                } catch (SQLException e) {
                    showErrorDialog("删除失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        } else {
            showWarningDialog("请选择要删除的行");
        }
    }

    /**
     * 重置密码
     */
    private void resetPassword() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow >= 0) {
            String username = (String) tableModel.getValueAt(selectedRow, 1);

            int confirm = showConfirmDialog(
                    "确定要重置用户 " + username + " 的密码吗?",
                    "确认重置");

            if (confirm == JOptionPane.YES_OPTION) {
                String sql = "UPDATE users SET password = ? WHERE username = ?";
                String defaultPassword = "000000"; // 默认密码

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement(sql)) {

                    pstmt.setString(1, defaultPassword);
                    pstmt.setString(2, username);

                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        showMessageDialog("密码已重置为默认值");
                    } else {
                        showErrorDialog("密码重置失败，未找到用户");
                    }
                } catch (SQLException e) {
                    showErrorDialog("密码重置失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        } else {
            showWarningDialog("请选择要重置密码的行");
        }
    }

    // 辅助方法：显示对话框
    private void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(this, message);
    }

    private void showErrorDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    private void showWarningDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "提示", JOptionPane.WARNING_MESSAGE);
    }

    private int showConfirmDialog(String message, String title) {
        return JOptionPane.showConfirmDialog(
                this, message, title, JOptionPane.YES_NO_OPTION);
    }
}

/**
 * 用户编辑对话框（使用动态SQL）
 */
class UserEditDialog extends JDialog {
    private JTextField usernameField;
    private JPasswordField passwordField, confirmPasswordField;
    private JComboBox<String> roleCombo;
    private boolean isEditMode;

    public UserEditDialog(String username) {
        setTitle(username == null ? "添加用户" : "编辑用户");
        isEditMode = username != null;

        setSize(400, 300);
        setModal(true);
        setLocationRelativeTo(null);

        // 初始化表单组件
        initFormComponents();

        if (isEditMode) {
            loadUserData(username);
        }
    }

    /**
     * 初始化表单组件
     */
    private void initFormComponents() {
        JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        if (isEditMode) {
            usernameField.setEditable(false); // 编辑模式下用户名不可编辑
        }
        panel.add(usernameField);

        panel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        panel.add(passwordField);

        panel.add(new JLabel("确认密码:"));
        confirmPasswordField = new JPasswordField();
        panel.add(confirmPasswordField);

        panel.add(new JLabel("角色:"));
        String[] roles = {"管理员", "普通用户", "操作员"};
        roleCombo = new JComboBox<>(roles);
        panel.add(roleCombo);

        // 添加按钮
        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(this::saveUser);

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void saveUser() {  // 移除参数
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        String role = (String) roleCombo.getSelectedItem();

        // 验证输入
        if (!validateInput(username, password, confirmPassword)) {
            return;
        }

        // 动态构建SQL
        StringBuilder sqlBuilder = new StringBuilder();
        List<Object> params = new ArrayList<>();

        if (isEditMode) {
            // 更新用户信息
            if (password.isEmpty()) {
                // 只更新角色
                sqlBuilder.append("UPDATE users SET role = ? WHERE username = ?");
                params.add(role);
                params.add(username);
            } else {
                // 更新角色和密码
                sqlBuilder.append("UPDATE users SET role = ?, password = ? WHERE username = ?");
                params.add(role);
                params.add(password);
                params.add(username);
            }
        } else {
            // 添加新用户
            sqlBuilder.append("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
            params.add(username);
            params.add(password);
            params.add(role);
        }

        // 执行SQL
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sqlBuilder.toString())) {

            // 设置参数
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                String message = isEditMode ?
                        (password.isEmpty() ? "用户信息已更新" : "用户信息和密码已更新") :
                        "用户添加成功";
                JOptionPane.showMessageDialog(this, message);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this,
                        isEditMode ? "更新失败，未找到用户" : "添加失败",
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this,
                    "操作失败: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }

    /**
     * 加载用户数据
     */
    private void loadUserData(String username) {
        String sql = "SELECT username, role FROM users WHERE username = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    usernameField.setText(rs.getString("username"));

                    // 设置角色选择
                    String role = rs.getString("role");
                    for (int i = 0; i < roleCombo.getItemCount(); i++) {
                        if (roleCombo.getItemAt(i).equals(role)) {
                            roleCombo.setSelectedIndex(i);
                            break;
                        }
                    }
                }
            }
        } catch (SQLException e) {
            showErrorDialog("加载数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 保存用户信息
     */
    private void saveUser(ActionEvent e) {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        String role = (String) roleCombo.getSelectedItem();

        // 验证输入
        if (!validateInput(username, password, confirmPassword)) {
            return;
        }

        // 动态构建SQL
        StringBuilder sqlBuilder = new StringBuilder();
        List<Object> params = new ArrayList<>();

        if (isEditMode) {
            // 更新用户信息
            if (password.isEmpty()) {
                // 只更新角色
                sqlBuilder.append("UPDATE users SET role = ? WHERE username = ?");
                params.add(role);
                params.add(username);
            } else {
                // 更新角色和密码
                sqlBuilder.append("UPDATE users SET role = ?, password = ? WHERE username = ?");
                params.add(role);
                params.add(password);
                params.add(username);
            }
        } else {
            // 添加新用户
            sqlBuilder.append("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
            params.add(username);
            params.add(password);
            params.add(role);
        }

        // 执行SQL
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sqlBuilder.toString())) {

            // 设置参数
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                String message = isEditMode ?
                        (password.isEmpty() ? "用户信息已更新" : "用户信息和密码已更新") :
                        "用户添加成功";
                showMessageDialog(message);
                dispose();
            } else {
                showErrorDialog(isEditMode ? "更新失败，未找到用户" : "添加失败");
            }
        } catch (SQLException ex) {
            showErrorDialog("操作失败: " + ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 验证输入数据
     */
    private boolean validateInput(String username, String password, String confirmPassword) {
        if (username.isEmpty()) {
            showErrorDialog("用户名不能为空");
            return false;
        }

        // 添加用户或修改密码时需要验证密码
        if (!isEditMode || !password.isEmpty()) {
            if (password.isEmpty()) {
                showErrorDialog("密码不能为空");
                return false;
            }

            if (!password.equals(confirmPassword)) {
                showErrorDialog("两次输入的密码不一致");
                return false;
            }

            if (password.length() < 6) {
                showErrorDialog("密码长度不能少于6位");
                return false;
            }
        }

        return true;
    }

    // 辅助方法：显示对话框
    private void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(this, message);
    }

    private void showErrorDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
}